<template>
  <el-dialog v-model="addOrEditVisible" :title="props.isEditor ? '编辑资产信息' : '新建资产信息'" width="800" class="dialog-box">
    <el-form
      v-if="!modalFormConfig.loading"
      :inline="true"
      ref="modalFormRef"
      label-width="auto"
      :model="modalForm"
      :rules="modalFormConfig.rules"
      class="form-box"
    >
      <el-form-item label="资源组名称" prop="group">
        <el-tree-select
          v-model="modalForm.group"
          style="width: 100%"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          :data="type.data"
          :props="type.replaceFields"
          check-strictly
          placeholder="请选择资源组名称"
        />
      </el-form-item>
      <template v-for="item of modalFormConfig.data" :key="item.key">
        <el-form-item :label="`${item.name}`" :prop="item.key" :class="getClass(item)">
          <el-input :value="userInfo.username" disabled v-if="item.key === 'creator'" allow-clear />
          <el-input
            v-else-if="item.key === 'other_info'"
            type="textarea"
            v-model="modalForm[item.key]"
            :placeholder="`请输入${item.name}`"
            :auto-size="{ minRows: 2, maxRows: 2 }"
            allow-clear
          />
          <el-input
            v-else-if="item.type === '字符串'"
            v-model="modalForm[item.key]"
            :placeholder="`请输入${item.name}`"
            allow-clear
          />
          <el-input-number
            style="width: 100%"
            v-else-if="item.type === '整数'"
            v-model="modalForm[item.key]"
            :precision="0"
            :step="1"
            :placeholder="`请输入${item.name}`"
          />
          <el-input-number
            style="width: 100%"
            v-else-if="item.type === '小数'"
            :step="0.01"
            :precision="2"
            v-model="modalForm[item.key]"
            :placeholder="`请输入${item.name}`"
          />
          <el-date-picker
            v-else-if="item.type === '日期'"
            format="YYYY-MM-DD HH:mm:ss"
            :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
            @change="val => onChange(item.key, val)"
          />
          <el-select
            v-else-if="item.type === '字典类'"
            v-model="modalForm[item.key]"
            :placeholder="`请选择${item.name}`"
            @change="val => onChange(item.key, val)"
            allow-clear
          >
            <el-option v-for="it of item.value" :key="it.id" :value="it.id" :label="it.value">{{ it.value }}</el-option>
          </el-select>
        </el-form-item>
      </template>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submit(modalFormRef)" :loading="loading">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="AddOrEdit">
import moment from "moment/moment";
import { computed, ref } from "vue";
import { getAssetCollect, getBaseDataList, create, update } from "@/api/modules/asset";
import { ElMessage, type FormInstance } from "element-plus";
const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  },
  isCopy: {
    type: Boolean,
    default: false
  },
  isEditor: {
    type: Boolean,
    default: false
  }
});
// emit
const emit = defineEmits<{
  refresh: [];
}>();
const addOrEditVisible = ref<boolean>(false);
const modalFormConfig = ref<any>({
  loading: false,
  data: [],
  rules: {
    group: [{ required: true, message: "内容不能为空", trigger: "change" }]
  }
});
const loading = ref<boolean>(false);
const type = { loading: false, data: null, replaceFields: { children: "children", label: "name", value: "id" } };
const modalForm = ref<any>({
  group: ""
});
const userInfo = computed(() => {
  const sysUser: any = localStorage.getItem("sys-user") || {};
  return JSON.parse(sysUser).userInfo;
});
const onChange = (key, value) => {
  if (key === "日期") {
    modalForm.value[key] = value.format("YYYY-MM-DD HH:mm:ss");
  } else {
    modalForm.value[key] = value;
  }
};
const initialForm = async () => {
  modalFormConfig.value.loading = true;
  modalForm.value = {};
  try {
    const { data } = await getBaseDataList();
    if (props.isEditor) {
      modalFormConfig.value.data = data.filter(item => item.key !== "creator");
    } else {
      modalFormConfig.value.data = data;
    }
    if (props.isCopy || props.isEditor) {
      modalForm.value.group = props.data.group;
    }
    modalFormConfig.value.data.forEach(item => {
      if (props.isCopy || props.isEditor) {
        let value = props.data[item.key] === null ? undefined : props.data[item.key];
        if (item.type === "字典类" && value) value = item.value.find(item => item.value === value).id;
        // this.$set(modalForm, item.key, value);
        modalForm.value[item.key] = value;
      } else {
        // this.$set(modalForm, item.key, undefined);
        modalForm.value[item.key] = undefined;
      }
      modalFormConfig.value.rules[item.key] = getFormRules(item);
      if (item.key === "creator") modalForm.value[item.key] = userInfo.value.id;
    });
    // this.$forceUpdate();
  } finally {
    modalFormConfig.value.loading = false;
  }
};
const getFormRules = item => {
  const out: any = [];
  if (!item.is_null) out.push({ required: true, message: "内容不能为空", trigger: "blur" });
  if (item.key !== "creator") {
    if (item.type === "字符串") out.push({ min: 0, max: 500, message: "长度为0~500个字符", trigger: "blur" });
    if (item.type === "整数") out.push({ type: "number", message: "请输入数字", trigger: "blur" });
  }
  return out;
};
const getClass = item => {
  let str = "";
  str += item.is_null ? "not-necessary " : "";
  str += item.key === "remark" || item.key === "other_info" ? "double" : "";
  return str;
};
const modalFormRef = ref<FormInstance>();
const submit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async val => {
    if (val) {
      loading.value = true;
      if (!props.isEditor) {
        const res = await create(modalForm.value);
        if (res) ElMessage.success("资产创建成功");
      } else {
        const res = await update(modalForm.value, props.data.id);
        if (res) ElMessage.success("资产编辑成功");
      }
      loading.value = false;
      emit("refresh");
      closeDialog();
    }
  });
};
// 请求资产类型树
const getTypeList = async () => {
  type.loading = true;
  try {
    const { data } = await getAssetCollect();
    type.data = data;
  } catch (error) {
    console.error(error);
    ElMessage.error("资产类型获取失败");
  } finally {
    type.loading = false;
  }
};
const openDialog = () => {
  addOrEditVisible.value = true;
  getTypeList();
  initialForm();
};
const closeDialog = () => {
  addOrEditVisible.value = false;
};
defineExpose({
  openDialog,
  closeDialog
});
</script>

<style scoped lang="scss">
.dialog-box {
  .form-box {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-gap: 4px;
    justify-content: center;
    .double {
      grid-column: span 2;
    }
    .not-necessary {
      .ant-form-item-required {
        &::before {
          display: none;
        }
      }
    }
    .ant-form-item-label {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
</style>
